package wonder.random;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;

import wonder.Board;
import wonder.ISWService.BoardSet;
import wonder.SWServiceFactory;
import wonder.tools.LoggerHelper;

public class InitialSetup {
	private static final Logger logger = LoggerHelper.getLogger();

	public static List<Board> randomize(int players, List<BoardSet> sets)
			throws Exception {
		List<Board> rc = new ArrayList<Board>();

		List<Board> selectedSetMaps = new LinkedList<Board>();

		// make sets unique
		Map<String, BoardSet> uSets = new HashMap<String, BoardSet>();
		for (BoardSet s : sets) {
			uSets.put(s.toString(), s);
		}

		// build the list of available WonderMaps
		for (Entry<String, BoardSet> es : uSets.entrySet()) {
			for (Board map : SWServiceFactory.getInstance().getSWService()
					.getBoards()) {
				if (es.getValue().equals(map.getSet()) && map.isAvailable()) {
					selectedSetMaps.add(map);
				}
			}
		}

		logger.trace("selectedSetMaps for #{} using Wonders:{}", players,
				selectedSetMaps);
		// verify players <= available maps
		if (selectedSetMaps.size() < 2 * players) {
			throw new IllegalArgumentException("Wonder sets " + sets
					+ " does not contain enough Wonders for players #"
					+ selectedSetMaps.size());
		}

		while (rc.size() < players) {
			rc.add(pickRandomBoard(selectedSetMaps));
		}
		return rc;
	}

	private static Board pickRandomBoard(List<Board> l) {
		int i = (int) (Math.random() * l.size());
		Board rc = l.get(i);

		l.remove(i);
		for (int j = 0; j < l.size(); j++) {
			Board b = l.get(j);
			if (b.getName().equals(rc.getName())) {
				l.remove(j);
				break;
			}
		}

		return rc;
	}
}
